/**
 * Copyright (C), 2020, Y2 T205
 * FileName: MyRabbitConfig
 * Author: Lenovo
 * Date: 2020-05-29 17:59
 * Description: rabbit的配置文件
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */


package com.atguigu.gulimall.ware.config;


import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.retry.annotation.Backoff;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈rabbit的配置文件〉
 *
 * @author Lenovo
 * @create 2020-05-29
 * @since 1.0.0
 */
@Configuration
public class MyRabbitConfig {


    //@Autowired
    RabbitTemplate rabbitTemplate;
    @Primary
    @Bean
   public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate =new RabbitTemplate(connectionFactory);
        this.rabbitTemplate=rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        return rabbitTemplate;
    }


    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();


    }

//    只要在有监听事件的处理的时候才会创建队列，否则不创建    创建玩之后，就注释掉，否则会变成消费者，使用消息，
/*@RabbitListener(queues = "stock.release.stock.queue")
public void hadle( Message message) {

}*/


//    在这个配置文件中创建交换机，队列，不用网站管理上创建啦

    @Bean    //交换机
    public Exchange stockEventExchange(){
        return new TopicExchange("stock-event-exchange",true,false);
    }

    @Bean  //普通队列
    public Queue StockReleaseStockQueue(){

        return new Queue("stock.release.stock.queue",true,false,false);
    }

    @Bean   //延迟队列
    public Queue stockDelayQueue(){
        Map<String,Object> args =new HashMap<>();
        args.put("x-dead-letter-exchange","stock-event-exchange");
        args.put("x-dead-letter-routing-key","stock.release");
        args.put("x-message-ttl",900000);   //调整定时关单的时间
        return new Queue("stock.delay.queue",true,false,false,args);
    }

    @Bean  //普通队列的绑定
    public Binding stockReleaseBinding(){
        return new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE,"stock-event-exchange","stock.release.#",null);
    }


    @Bean  //延时队列的绑定
    public Binding stockLockedBinding(){
        return new Binding("stock.delay.queue", Binding.DestinationType.QUEUE,"stock-event-exchange","stock.locked",null);
    }



}
